package com.example.demo.web;

import com.example.demo.exception.LoginException;
import com.example.demo.exception.ServiceException;
import com.example.demo.service.ITokenService;
import com.example.demo.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 父级控制器,每个控制器需要继承这个类
 */
public class BaseController {

    @Autowired private ITokenService tokenService;

    /**
     * 登录验证
     * @param token
     * @return
     * @throws LoginException
     * @throws ServiceException
     */
    public String verification(String token)throws LoginException, ServiceException{
        return this.tokenService.verification(token);
    }

    /**
     * 统一处理控制器层的ControllerException异常
     *
     * @param e
     * @return json数据
     */
    @ExceptionHandler(Exception.class)
    public Json<Void> controllerExceptionHandle(Exception e) {
        Json<Void> json = new Json<Void>();
        json.setData(null);
        if(e instanceof ServiceException){
            json.setMessage(e.getMessage());
            json.setState(400);
        }else if(e instanceof LoginException){
            json.setMessage(e.getMessage());
            json.setState(440);
        }else {
            e.printStackTrace();
            json.setMessage("服务器错误");
            json.setState(500);
        }
        return json;
    }

}
